<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import CrudTable from '../components/CrudTable.vue'
import FormDialog from '../components/FormDialog.vue'
import { listUsertable, getUsertable, addUsertable, updateUsertable, delUsertable } from '../api/usertable'
import { listDepartment } from '../api/department'
import { listRole } from '../api/role'

// 表格数据
const tableData = ref([])
// 表格加载状态
const loading = ref(false)
// 部门列表
const departmentList = ref([])
// 角色列表
const roleList = ref([])
// 对话框可见性
const dialogVisible = ref(false)
// 是否为编辑模式
const isEdit = ref(false)
// 表单加载状态
const formLoading = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  userName: '',
  password: '',
  gender: 0,
  roleId: null,
  departmentId: null
})

// 表单校验规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  departmentId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ]
}

// 表格列配置
const columns = [
  { prop: 'id', label: 'ID', width: '80' },
  { prop: 'userName', label: '用户名', width: '120' },
  { prop: 'gender', label: '性别', width: '80', formatter: (row) => row.gender === 0 ? '男' : '女' },
  { prop: 'roleId', label: '角色', formatter: (row) => {
    const role = roleList.value.find(item => item.id === row.roleId)
    return role ? role.roleName : '-'
  }},
  { prop: 'departmentId', label: '所属科室', formatter: (row) => {
    const dept = departmentList.value.find(item => item.id === row.departmentId)
    return dept ? dept.departmentName : '-'
  }},
  { prop: 'createTime', label: '创建时间', width: '180' }
]

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true
  try {
    tableData.value = await listUsertable()
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门列表
const fetchDepartmentList = async () => {
  try {
    departmentList.value = await listDepartment()
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

// 获取角色列表
const fetchRoleList = async () => {
  try {
    roleList.value = await listRole()
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    userName: '',
    password: '',
    gender: 0,
    roleId: null,
    departmentId: null
  })
}

// 处理新增
const handleAdd = () => {
  resetFormData()
  isEdit.value = false
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    const userDetail = await getUsertable(row.id)
    Object.assign(formData, userDetail)
    isEdit.value = true
    dialogVisible.value = true
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await delUsertable(row.id)
    ElMessage.success('删除成功')
    fetchTableData()
  } catch (error) {
    console.error('删除用户失败:', error)
    ElMessage.error('删除用户失败')
  }
}

// 处理表单提交
const handleSubmit = async () => {
  formLoading.value = true
  try {
    if (isEdit.value) {
      await updateUsertable(formData)
      ElMessage.success('更新成功')
    } else {
      await addUsertable(formData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchTableData()
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error('保存用户失败')
  } finally {
    formLoading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchTableData()
  fetchDepartmentList()
  fetchRoleList()
})
</script>

<template>
  <div class="home-container">
    <crud-table
      :data="tableData"
      :columns="columns"
      :loading="loading"
      title="用户管理"
      @add="handleAdd"
      @edit="handleEdit"
      @delete="handleDelete"
      @refresh="fetchTableData"
    >
      <!-- 表单对话框 -->
      <form-dialog
        v-model:visible="dialogVisible"
        :form-data="formData"
        :rules="rules"
        :is-edit="isEdit"
        :loading="formLoading"
        title="用户"
        @submit="handleSubmit"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="formData.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属科室" prop="departmentId">
          <el-select v-model="formData.departmentId" placeholder="请选择科室" style="width: 100%">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.departmentName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </form-dialog>
    </crud-table>
  </div>
</template>

<style scoped>
.home-container {
  padding: 20px;
}
</style> 